package com.xizi.forum.controller;


import com.xizi.forum.common.AppResult;
import com.xizi.forum.common.Constants;
import com.xizi.forum.common.ResultCode;
import com.xizi.forum.exception.ApplicationException;
import com.xizi.forum.model.MessageInfo;
import com.xizi.forum.model.UserInfo;
import com.xizi.forum.service.IMessageInfoService;
import com.xizi.forum.service.IUserService;
import com.xizi.forum.utils.StringUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;


// 站内信模块
@RestController
@RequestMapping("/message")
@Slf4j
public class MessageInfoController {

    @Autowired
    private IMessageInfoService messageInfoService;
    @Autowired
    private IUserService userService;

    /**
     * 创建站内信
     * @param request
     * @param receiveUserId 收信用户id
     * @param content 内容
     * @return
     */
    @PostMapping("/send")
    public AppResult send(HttpServletRequest request, @NonNull Long receiveUserId, @NonNull String content){
        //校验用户是否登入
        HttpSession session = request.getSession(false);
        if(session == null || session.getAttribute(Constants.USERINFO) == null){
            throw new ApplicationException(ResultCode.FAILED_NOT_LOGIN);
        }
        UserInfo userInfo = (UserInfo) session.getAttribute(Constants.USERINFO);
        //1.如果当前用户处于禁言状态不能发消息
        if(userInfo.getState() == 1){
            log.info(ResultCode.FAILED_USER_BANNED.toString());
            throw new ApplicationException(ResultCode.FAILED_USER_BANNED);
        }
        //2.不能发给自己
        if(receiveUserId == userInfo.getId()){
            log.warn("自己不能发给自己消息哦");
            throw new ApplicationException("自己不能发给自己消息哦");
        }
        //3.不能发给已删除或不存在的用户
        UserInfo receiveUser = userService.selectUserInfoById(receiveUserId);
        if(receiveUser == null || receiveUser.getDeleteState() == 1){
            throw new ApplicationException("接受消息的用户状态不正常，请不要发送消息");
        }

        MessageInfo messageInfo = new MessageInfo();
        messageInfo.setContent(content);
        messageInfo.setPostUserId(userInfo.getId());
        messageInfo.setReceiveUserId(receiveUserId);

        Boolean check = messageInfoService.create(messageInfo);

        return AppResult.success();
    }

    /**
     * 获取站内信未读的数量
     * @param request
     * @return
     */
    @GetMapping("/getUnreadCount")
    public AppResult getUnreadCount(HttpServletRequest request){
        HttpSession session = request.getSession(false);
        UserInfo userInfo = (UserInfo) session.getAttribute(Constants.USERINFO);

        Long count = messageInfoService.selectUnreadCount(userInfo.getId());

        return AppResult.success(count);
    }

    /**
     * 获取所有站内信
     * @param request
     * @return
     */
    @GetMapping("/getAll")
    public AppResult getAll(HttpServletRequest request){
        HttpSession session = request.getSession(false);
        UserInfo userInfo = (UserInfo) session.getAttribute(Constants.USERINFO);

        List<MessageInfo> list = messageInfoService.getAllMessageByUserId(userInfo.getId());
        return AppResult.success(list);
    }

    /**
     * 修改站内信状态
     * @param request
     * @param id 当前站内信id
     * @return
     */
    @PostMapping("/markRead")
    public AppResult markRead(HttpServletRequest request,@NonNull Long id){
        //1.参数校验
        if(id < 0){
            throw new ApplicationException(ResultCode.FAILED_PARAMS_VALIDATE);
        }
        //2.校验站内信状态
        MessageInfo messageInfo = messageInfoService.selectById(id);
        if(messageInfo == null || messageInfo.getDeleteState() == 1){
            log.info(ResultCode.FAILED_NOT_EXISTS.toString());
            throw new ApplicationException(ResultCode.FAILED_NOT_EXISTS);
        }
        //3.校验当前登入用户 与 收信者是否一致
        HttpSession session = request.getSession(false);
        UserInfo userInfo = (UserInfo) session.getAttribute(Constants.USERINFO);
        if(userInfo.getId() != messageInfo.getReceiveUserId()){
            log.error("访问到了不是当前登入者的站内信 userId = " + userInfo.getId() + ",messageId" + messageInfo.getId());
            throw new ApplicationException(ResultCode.FAILED_SERVICE);
        }
        //4.进行修改
        messageInfoService.updateStateById(id, (byte) 1);
        return AppResult.success();
    }

    /**
     * 站内信回复
     * @param request
     * @param repliedId 回信用户id
     * @param receiveUserId 收信用户id
     * @param content 内容
     * @return
     */
    @PostMapping(value = "reply",produces = "application/json")
    public AppResult reply(HttpServletRequest request,Long repliedId,Long receiveUserId,String content){
        //1.参数校验
        if(repliedId == null || repliedId <= 0 || receiveUserId == null || receiveUserId <= 0 || StringUtil.isEmpty(content)){
            log.info(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(ResultCode.FAILED_PARAMS_VALIDATE);
        }
        HttpSession session = request.getSession(false);
        UserInfo useInfo = (UserInfo) session.getAttribute(Constants.USERINFO);
        //2.校验是不是给自己回复
        if(useInfo.getId() == receiveUserId){
            log.warn("自己给自己回复消息了userId : {},receiveUserId: {}",useInfo.getId(),receiveUserId);
        }

        MessageInfo messageInfo = new MessageInfo();
        messageInfo.setPostUserId(useInfo.getId());
        messageInfo.setReceiveUserId(receiveUserId);
        messageInfo.setContent(content);
        messageInfoService.reply(repliedId,messageInfo);

        return AppResult.success();
    }

    /**
     * 通过id删除站内信（逻辑删除）
     * @param id
     * @return
     */
    @PostMapping("/deleteById")
    public AppResult deleteById(Long id){
        // 1.参数校验
        if(id == null || id <= 0){
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(ResultCode.FAILED_PARAMS_VALIDATE);
        }

        messageInfoService.deleteById(id);
        log.info("删除站内信成功！");
        return AppResult.success();
    }
}
